#include "strExt.h"

int indexof(const char *s, const char *t)
{
    if(s == NULL || t == NULL) return -1;

    char *p = strstr(s, t);
    /* use memory position to implement */
    return (p == NULL) ? -1 : (p - s);
}

int lastindexof(const char *s, const char *t)
{
    int index = -1;
    if(s == NULL || t == NULL) return index;

    char *p = strstr(s, t);
    while(p != NULL)
    {
        index = p - s;
        p++;
        p = strstr(p, t);
    }

    return index;
}

int startwith(const char *s, const char *t)
{
    return indexof(s, t);
}

int endwith(const char *s, const char *t)
{
    if(s == NULL || t == NULL) return -1;
    int slen = strlen(s);
    int tlen = strlen(t);
    if(tlen > slen) return -1;
    return (0 == strcmp(s + slen - tlen, t)) ? 0 : -1;
}

void ltrim(char *s)
{
    int i;
    int count = 0;
    int size = strlen(s);
    while(s[count] != '\0')
    {
        /* 32 space, 9 tab */
        if(s[count] != 32 && s[count] != 9) break;
        count++;
    } 
    if(count == 0) return;
    for(i = 0; i <= size - count; i++)
    {
        s[i] = s[i + count];
    }
}

void rtrim(char *s)
{
    int i = strlen(s) - 1;
    while(i >= 0)
    {
        /* 32 space, 9 tab */
        if(s[i] != 32 && s[i] != 9) break;
        i--;
    }
    s[++i] = '\0';
}

void trim(char *s)
{
    ltrim(s);
    rtrim(s);
}
